package com.cdvtc.forum_system.dao.Impl;

import com.cdvtc.forum_system.dao.UserDao;
import com.cdvtc.forum_system.model.User;
import com.cdvtc.forum_system.util.DBUtil;
import com.cdvtc.forum_system.util.Md5Util;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    @Override
    public User login(String user_account, String user_password) {
        User user = null;
        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        user_password = Md5Util.md5(user_password);
        System.out.println(user_password);
        try {
            con = DBUtil.getConnection();
            // 修正 SQL 条件分组，确保逻辑正确
            String sql = "select * from user where (user_account=? or user_mobile=? or user_email=?) and user_password=? and user_forbidden=?";
            pst = con.prepareStatement(sql);
            pst.setString(1, user_account);
            pst.setString(2, user_account);
            pst.setString(3, user_account);
            pst.setString(4, user_password);
            pst.setInt(5, 0);
            rs = pst.executeQuery();
            if (rs.next()) {
                user = new User();
                user.setUser_id(rs.getInt("user_id"));
                user.setUser_account(rs.getString("user_account"));
                user.setUser_nickname(rs.getString("user_nickname"));
                user.setUser_password(rs.getString("user_password"));
                user.setUser_photo(rs.getString("user_photo"));
                user.setUser_birthday(rs.getDate("user_birthday"));
                user.setUser_email(rs.getString("user_email"));
                user.setUser_mobile(rs.getString("user_mobile"));
                user.setUser_regdate(rs.getTimestamp("user_regdate"));
                user.setForbidden(rs.getBoolean("user_forbidden"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 统一规范资源释放
            DBUtil.release(rs, pst, con);
        }
        return user;
    }

    // 新增：根据用户ID获取用户信息（用于显示昵称和头像）
    @Override
    public User getUserById(int user_id) {
        User user = null;
        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            con = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE user_id = ?";
            pst = con.prepareStatement(sql);
            pst.setInt(1, user_id);
            rs = pst.executeQuery();

            if (rs.next()) {
                user = new User();
                user.setUser_id(rs.getInt("user_id"));
                user.setUser_account(rs.getString("user_account"));
                user.setUser_nickname(rs.getString("user_nickname"));
                user.setUser_photo(rs.getString("user_photo"));
                // 其他字段按需获取
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.release(rs, pst, con);
        }
        return user;
    }

    @Override
    public boolean addUser(User user) {
        Connection con = null;
        PreparedStatement pst = null;
        try {
            con = DBUtil.getConnection();
            if (con == null) {
                System.out.println("数据库连接获取失败！");
                return false;
            }

            // 使用自增主键，排除 user_id 字段
            String sql = "insert into user(user_account, user_nickname, user_password, user_photo, user_birthday, user_email, user_mobile, user_regdate, user_forbidden) values(?, ?, ?, ?, ?, ?, ?, ?, ?)";
            pst = con.prepareStatement(sql);

            // 设置参数（注意索引从1开始）
            pst.setString(1, user.getUser_account());
            pst.setString(2, user.getUser_nickname());
            pst.setString(3, user.getUser_password());
            pst.setString(4, user.getUser_photo());

            // 处理可能为 null 的生日字段
            java.sql.Date birthday = user.getUser_birthday() != null
                    ? new java.sql.Date(user.getUser_birthday().getTime())
                    : new java.sql.Date(System.currentTimeMillis());
            pst.setDate(5, birthday);

            pst.setString(6, user.getUser_email());
            pst.setString(7, user.getUser_mobile());

            // 使用用户注册时间或当前时间
            java.sql.Timestamp regdate = user.getUser_regdate() != null
                    ? new java.sql.Timestamp(user.getUser_regdate().getTime())
                    : new java.sql.Timestamp(System.currentTimeMillis());
            pst.setTimestamp(8, regdate);

            pst.setBoolean(9, user.getForbidden());

//            System.out.println(pst.getMetaData());

            int result = pst.executeUpdate();
            return result > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.release(null, pst, con);
        }
    }

    @Override
    public boolean isUserExisted(String key, String value) {
        boolean existed = false;
        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            con = DBUtil.getConnection();
            // 校验 key ，保证传入合法的查询条件字段
            if ("user_account".equals(key) || "user_nickname".equals(key) || "user_password".equals(key)) {
                String sql = "select * from user where " + key + "=?";
                pst = con.prepareStatement(sql);
                pst.setString(1, value);
                rs = pst.executeQuery();
                existed = rs.next();
            } else {
                throw new IllegalArgumentException("key 只能是 account、nickname、password 对应的数据库字段名（user_account、user_nickname、user_password）");
            }
        } catch (SQLException | IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            DBUtil.release(rs, pst, con);
        }
        return existed;
    }

    @Override
    public List<User> getAllUsers() {
        List<User> users = new ArrayList<>();
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            con = DBUtil.getConnection();
            st = con.createStatement();
            String sql = "select * from user";
            rs = st.executeQuery(sql);
            while (rs.next()) {
                User user = new User();
                user.setUser_id(rs.getInt("user_id"));
                user.setUser_account(rs.getString("user_account"));
                user.setUser_nickname(rs.getString("user_nickname"));
                user.setUser_password(rs.getString("user_password"));
                user.setUser_photo(rs.getString("user_photo"));
                user.setUser_birthday(rs.getDate("user_birthday"));
                user.setUser_mobile(rs.getString("user_email"));
                user.setUser_mobile(rs.getString("user_mobile"));
                user.setUser_regdate(rs.getTimestamp("user_regdate"));
                user.setForbidden(rs.getBoolean("user_forbidden"));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.release(rs, (PreparedStatement) st, con);
        }
        return users;
    }

    @Override
    public void forbiddenUser(int user_id, boolean user_forbidden) {
        Connection con = null;
        PreparedStatement pst = null;
        try {
            con = DBUtil.getConnection();
            String sql = "update user set user_forbidden=? where user_id=?";
            pst = con.prepareStatement(sql);
            pst.setBoolean(1, user_forbidden);
            pst.setInt(2, user_id);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.release(null, pst, con);
        }
    }

    @Override
    public void forgetPassword(String account, String nickname) {
        Connection con = null;
        PreparedStatement pst = null;
        try {
            con = DBUtil.getConnection();
            // 这里示例是简单重置密码为 "123456" ，实际应结合加密逻辑处理
            String sql = "update user set user_password=? where user_account=? and user_nickname=?";
            pst = con.prepareStatement(sql);
            pst.setString(1, "123456");
            pst.setString(2, account);
            pst.setString(3, nickname);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.release(null, pst, con);
        }
    }

    @Override
    public void updateUser(User user) {
        Connection con = null;
        PreparedStatement pst = null;
        try {
            con = DBUtil.getConnection();
            String sql = "update user set user_nickname=?, user_photo=?, user_birthday=?, user_email=?, user_mobile=? where user_account=?";
            pst = con.prepareStatement(sql);
            pst.setString(1, user.getUser_nickname());
            pst.setString(2, user.getUser_photo());
            pst.setDate(3, new Date(user.getUser_birthday().getTime()));
            pst.setString(4, user.getUser_email());
            pst.setString(5, user.getUser_mobile());
            pst.setString(6, user.getUser_account());
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.release(null, pst, con);
        }
    }

    public static void main(String[] args) {
        UserDao userDao = new UserDaoImpl();
        // 简单测试，实际根据情况调整参数
        System.out.println(userDao.login("food001", "e10adc3949ba59abbe56e057f20f883e"));
        System.out.println(userDao.isUserExisted("user_account", "food001"));
    }
}